﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Model;
using Ysb.Components;
using BLL;
using Aspose.Cells;
using System.Text.RegularExpressions;
public partial class Admin_Default : System.Web.UI.Page
{
    string id;
    Tools tool = new Tools();
    PublicSqlService ps = new PublicSqlService();
    protected void Page_Load(object sender, EventArgs e)
    {
	
	 if (Session["UserName"].ToString() == "Tom Liu" || Session["UserName"].ToString() == "小容" || Session["UserName"].ToString() == "路得" || Session["UserName"].ToString() == "steven" || Session["UserName"].ToString() == "Chris Wu" || Session["UserName"].ToString() == "amy"
   )
                 {
                 }
                 else
                 {
       payall.Attributes.Add("readonly", "readonly");
	   name.Attributes.Add("readonly", "readonly");
	   acctxt.Attributes.Add("readonly", "readonly");
	         


                 }
				 
        if (!AdminCheck.Check(this, 1))
        {

            Response.Redirect(AdminCheck.RedirectPage);
            return;
        }
        if (!Page.IsPostBack)
        {
            selectpaytype.DataSource = new PublicSqlService().GetData("*", "tbl_Paytype", "");
            selectpaytype.DataTextField = "Name";
            selectpaytype.DataValueField = "Name";
            selectpaytype.DataBind();
            DataLoad();
            id = "12";//设置为公司ID
            usershow.InnerHtml = Session["UserName"].ToString();
        }
    }
    private void DataLoad()
    {
        PublicSqlService ps = new PublicSqlService();

        lylb.Text = ps.GetCoun("ID", "Tbl_UserDiscussTheme", "UPEXIsRead=0").ToString();
        ydlylb.Text = ps.GetCoun("DID", "Tbl_Discuss", "UPEXIsRead=0").ToString();

        ydcl.Text = ps.GetCoun("BID", "Tbl_WayBill", "StateId=1").ToString();
        shkh.Text = ps.GetCoun("UID", "TblUserInfo", "UserState=0").ToString();



    }
    protected void okbtn_Click(object sender, ImageClickEventArgs e)
    {



        string name = "";

        UploadFile up = new UploadFile(".xls", 10000, "temp");
        if (up.UpLoad(fileselecet))
        {
            name = up.FileName;
        }
        else
        {
            Tools.OpenWindow(this, up.ErrorMessage);
            return;
        }



        ToExcel(name);


    }

    void ToExcel(string nme)
    {


        try
        {


            Workbook wb = new Workbook();

            wb.LoadData(ApplicationInfo.PhysicalApplicationPath + "\\Temp\\" + nme);
            Worksheet ws = wb.Worksheets[0];
            //   Worksheet ws1 = wb.Worksheets[1];



            DataTable dt = ws.Cells.ExportDataTable(0, 0, ws.Cells.MaxDataRow + 1, ws.Cells.MaxColumn + 1, true);
            InsertBill(dt);
        }
        catch
        {
            Tools.OpenWindow(this, "模板错误！请选择正确模板");
        }

    }
    void InsertBill(DataTable dt)
    {


        if (dt.Columns.Count != 34)
        {
            Tools.OpenWindow(this, "单据模板错误！请重新下载");
            return;
        }
        PublicSqlService ps = new PublicSqlService();
        Hashtable hs = new Hashtable();
        int ok = 0;
        string err = "";
        int cont = 0;
        int bcount = 0;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            cont++;
            hs.Clear();
            string n = dt.Rows[i][0].ToString().Trim();
            if (n == "")
            {
                bcount++;
                continue;
            }
            Regex rg = new Regex("^[0-9]{10}$");

            if (!rg.IsMatch(n))
            {
                bcount++;
                continue;
            }

            if (ps.GetCoun("BID", "Tbl_WayBill", "TrackingNo='" + n + "'") != 0)
            {
                if (relaceselect.SelectedItem.Value.Trim() == "2")
                {
                    //如果是选择保留 跳过
                    bcount++;
                    continue;

                }
                else
                {
                    //替换，删除以前数据
                    ps.Del("Tbl_WayBill", "TrackingNo='" + n + "'");
                }
            }
            if (dt.Rows[i][1].ToString().Trim() == "")
            {
                bcount++;
                continue;

            }


            string userid = new PublicSqlService().GetWords("TblUserInfo", "UID", "AccountNo='" + dt.Rows[i][1].ToString().Trim() + "'");
            if (userid.Trim() == "")
            {
                bcount++;
                continue;
            }
            hs.Add("CreateUserID", userid);
            hs.Add("CreateDate", DateTime.Now);
            hs.Add("AccountNo", dt.Rows[i][1]);
            hs.Add("TrackingNo", n);
            #region   发送人基本属性
            hs.Add("Sender", dt.Rows[i][2]);//名字C
            hs.Add("FromFaxNo", "");
            hs.Add("FromPhoneNo", dt.Rows[i][3]);//电话 D
            hs.Add("FromCompany", dt.Rows[i][4]);//公司/E
            hs.Add("FromAddress", dt.Rows[i][5]);//地址F
            hs.Add("FromCity", "");
            hs.Add("FromState", "");

            hs.Add("FromZIPCode", "");
            #endregion
            #region   收件人基本属性

            hs.Add("Receiver", dt.Rows[i][6]);//收件人 G
            hs.Add("ToPhoneNo", dt.Rows[i][7]);//收件电话H
            hs.Add("ToCompany", dt.Rows[i][8]);//i
            hs.Add("ToAddress", dt.Rows[i][9]);//j
            hs.Add("ToCity", "");
            hs.Add("ToState", "");
            hs.Add("ToCountry", "");
            hs.Add("ToZIPCode", "");
            #endregion
            #region 其他相关属性
            hs.Add("FlightNo", dt.Rows[i][10]);//参考K
            hs.Add("AerialNo", dt.Rows[i][13]);//航空单号N
            // hs.Add("CreateUserID", id);
            hs.Add("Origin", dt.Rows[i][11]);//L
            hs.Add("Destination", dt.Rows[i][12]);//M
            //支付方式
            string pay = "1";
            string zf = dt.Rows[i][19].ToString().Trim();
            int sz = new Tools().StringToIntDif(zf, -10);
            if (sz == -10)
            {
                //不是数字

                string pid = ps.GetWords("Tbl_PayModel", "PID", "ModelName='" + zf + "'");
                if (pid.Trim() != "")
                {
                    pay = pid;
                }
            }
            else
            {
                if (sz > 0 && sz < 5)
                {
                    pay = sz.ToString();
                }

            }


            hs.Add("Payment", pay);//T




            hs.Add("Sep", 0);
            //包装形式

            string pk = "0";
            switch (dt.Rows[i][15].ToString().Trim())
            {
                case "0":
                    pk = "0";
                    break;
                case "1":
                    pk = "1";
                    break;
                case "2":
                    pk = "2";
                    break;
                case "文件":
                    pk = "0";
                    break;
                case "私人包裹":
                    pk = "1";
                    break;
                case "商业样品":
                    break;
                    pk = "2";
                    break;

            }
            hs.Add("Packing", pk);//P






            hs.Add("DestPaidBy", 0);

            //保价费








            hs.Add("ShipmentInsurance", 0);

            hs.Add("InsurancePrice", 0);


            hs.Add("InsuredValue", 0);





            #endregion
            #region 质量 体积
            hs.Add("NoOfPiece", 1); //默认1 有分单  按照分单数计算
            hs.Add("TotalWeight", tool.StringToDecimalDif(dt.Rows[i][14]));//重重量O
            hs.Add("DimensionsH", tool.StringToDecimalDif(dt.Rows[i][16]));//q
            hs.Add("DimensionsL", tool.StringToDecimalDif(dt.Rows[i][17]));//r
            hs.Add("DimensionsW", tool.StringToDecimalDif(dt.Rows[i][18]));//s

            hs.Add("DimensionsStyle", 0);

            hs.Add("DimensionsWeight", 0);//体积重量

            #endregion
            #region  价格
            hs.Add("ChargedWt", tool.StringToDecimalDif(dt.Rows[i][21]));//收费重量V
            // hs.Add("DeclarePrice", (tool.StringToDecimalDif(StrHelper.VldNull(allprice.Text.Trim())) > PirceSum * PriceRate) ? PirceSum * PriceRate : tool.StringToDecimalDif(StrHelper.VldNull(allprice.Text.Trim())));
            hs.Add("FreightCharge", tool.StringToDecimalDif(dt.Rows[i][23]));//重量收费x
            hs.Add("DeclarePrice", tool.StringToDecimalDif(dt.Rows[i][33]));//海关申报价AH
            hs.Add("Memo2", tool.StringToDecimalDif(dt.Rows[i][24]));//垫付费Y
            hs.Add("Memo3", tool.StringToDecimalDif(dt.Rows[i][25]));//代购费Z
            hs.Add("Memo4", tool.StringToDecimalDif(dt.Rows[i][26]));//包装费AA
            hs.Add("Duties", tool.StringToDecimalDif(dt.Rows[i][27]));//关税AB
            hs.Add("Premium", tool.StringToDecimalDif(dt.Rows[i][28]));//保险费ac
            hs.Add("OtherCharge", tool.StringToDecimalDif(dt.Rows[i][29]));//其他费用AD
            hs.Add("Memo5", tool.StringToDecimalDif(dt.Rows[i][30]));//优惠//AE
            hs.Add("Total", tool.StringToDecimalDif(dt.Rows[i][20]));//总费用U
            #endregion
            #region  状态
            hs.Add("BankID", 1);
            hs.Add("UPEXState", "可编辑");
            hs.Add("BillState", 1);
            hs.Add("IsPlot", 0);
            hs.Add("StateId", 1);
            hs.Add("Complete", 0);
            hs.Add("BillingCopyDate", DateTime.Now);




            if (new PublicSqlService().Insert(hs, "Tbl_WayBill"))
            {


                new WayBillService().UPBillPriceByTno(n);
                ps.Del("TblShipment", "TrackingNo='" + n + "'");
                hs.Clear();
                hs.Add("TrackingNo", n);
                hs.Add("Commodity", dt.Rows[0][31]);//Af
                hs.Add("Qty", tool.StringToIntDif(dt.Rows[0][32]));//Ag
                hs.Add("UnitValue", 0);
                hs.Add("ValueForCustoms", tool.StringToDecimalDif(dt.Rows[0][33]));//AH
                ps.Insert(hs, "TblShipment");


                ok++;
            }
            else
            {
                err += "," + n;
            }

            #endregion

        }
        Tools.OpenWindow(this, "单据导入完成：<br/>成功保存单据数据量：" + ok + "<br/> 数据行：" + cont + " 其中 跳过数据：" + bcount.ToString() + "<br/>保存失败单据：<br/>" + err + "<br/>无法导入的数据请检查单号");


    }
    //状态导入
    void InsertState(DataTable dt)
    {
        Hashtable hs = new Hashtable();

        int iok = 0;
        int editok = 0;
        string err = "";
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i][0].ToString().Trim() == "")
            {
                continue;
            }
            hs.Clear();
            hs.Add("SepNo", dt.Rows[i][0].ToString());
            hs.Add("Date", tool.StringToTime(dt.Rows[i][1].ToString()));
            hs.Add("RecordDate", DateTime.Now);
            hs.Add("RecorderID", Session["uid"].ToString());
            hs.Add("CompanyNo", dt.Rows[i][3].ToString());
            hs.Add("CompanyID", dt.Rows[i][2].ToString());
            if (ps.GetCoun("BSRID", "Tbl_BillStateRec", "SepNo='" + dt.Rows[i][0].ToString() + "' and StateID=" + dt.Rows[i][2].ToString()) != 0)
            {
                //有
                if (relaceselect.SelectedItem.Value.Trim() == "1")
                {

                    //替换

                    if (ps.Update(hs, "Tbl_BillStateRec", "SepNo='" + dt.Rows[i][0].ToString() + "' and StateID=" + dt.Rows[i][2].ToString()))
                    {
                        editok++;
                    }
                    else
                    {
                        err += "," + dt.Rows[i][0].ToString();
                    }

                }
                else
                {
                    continue;
                }
            }

            else
            {
                //无
                if (ps.Insert(hs, "Tbl_BillStateRec"))
                {
                    iok++;
                }
                else
                {
                    err += "," + dt.Rows[i][0].ToString();
                }

            }


        }


        Tools.OpenWindow(this, "单据状态导入完成：<br/>写入状态数据量：" + iok + "<br/>编辑状态数量：" + editok + "<br/> 保存失败单据状态：<br/>" + err);


  
    }
    protected void paybtn_Click(object sender, ImageClickEventArgs e)
    {
        if (acctxt.Value.Trim() == "")
        {
            Tools.OpenWindow(this, "请输入账号");
            return;
        }
        if (name.Value.Trim() == "")
        {
            Tools.OpenWindow(this, "请输入姓名");
            return;
        }
        if (payall.Value.Trim() == "")
        {
            Tools.OpenWindow(this, "请输入支付总额");
            return;
        }
        Tools t = new Tools();


        string value = ps.GetWords("TblUserInfo", "Uid", "  AccountNo='" + acctxt.Value.Trim() + "'   and TrueName='" + name.Value.Trim() + "' ");

        if (value.Trim() == "")
        {
            Tools.OpenWindow(this, "当前并无此账号信息！");
            return;
        }

        int i = ps.GetMax("ID", "Tb_Pay", "");

        int all = 20000 + i;
        Hashtable hs = new Hashtable();

        hs.Add("AccountNo", all.ToString());
        hs.Add("UserID", value);
        hs.Add("PayAll", t.StringToDecimalDif(payall.Value.Trim()));
        hs.Add("PayType", selectpaytype.Value);
        hs.Add("ReMark", payabout.Value);
        hs.Add("PayDate", t.StringToTime(paydate.Value + " 05:30:50"));
        hs.Add("PostUser", 1);
        hs.Add("PostDate", DateTime.Now);
        if (ps.GetCoun("ID", "Tb_Pay", "AccountNo='" + all.ToString() + "'") > 0)
        {
            Tools.OpenWindow(this, "网络延迟。。账号重复，请重试");
            return;
        }
        if (ps.Insert(hs, "Tb_Pay"))
        {

            Tools.OpenWindow(this, "保存成功", Request.Url.ToString());
        }
        else
        {
            Tools.OpenWindow(this, "保存失败！");
        }





    }
}
